-- FreeSWITCH dialplan example
-- QQ: 1053481745
--get destination number
dest_num = argv[1]

session:execute("set", "hangup_after_bridge=true")
session:execute("set", "rtp_timeout_sec=20")
session:execute("record_session", "/app/dongsn/recordings/${strftime(%Y-%m-%d-%H-%M-%S)}_${caller_id_number}-${destination_number}.wav")
--session:execute("set", "proxy_media=true")

local dbh = freeswitch.Dbh("freeswitch2","root","root_21")

local dest_prefix = string.sub(dest_num, 1, 3)
freeswitch.consoleLog("warning", "dest_prefix: "..dest_prefix.. "\n")

--get callee_field from db
local gateway_query=string.format("select * from carrier where callee_prefix='%s' limit 1", dest_prefix);
dbh:query(gateway_query, function(callee)
	dial_param = callee.dial_param
	gateway_prefix = callee.gateway_prefix;
	gateway_ip = callee.gateway_ip
	gateway_port = callee.gateway_port
	end)

if(gateway_port and gateway_ip) then
	callee_field = dial_param.."sofia/internal/"..gateway_prefix..dest_num.."@"..gateway_ip..":"..gateway_port
else
	--registed members
	callee_field = "user/"..dest_num
end

if (dest_prefix ~= "con") then
	freeswitch.consoleLog("warning", "callee_field: " ..callee_field.. "\n")
	session:execute("bridge", callee_field)
else
	--conference test
	session:execute("answer")
	session:execute("conference", dest_num)
end

-- hangup when bridged done
if (session) then
	if (session:ready() == true) then session:hangup() end
end
